package handlers

import (
	"html/template"
	"strconv"

	"github.com/yjp211/web"

	"mutu/misc/cstore"
	"mutu/misc/log"
	"mutu/misc/typedef"
	"mutu/models"
	"mutu/service"
)

type UploadView struct{}

var (
	UploadHandler = UploadView{}
)

func (p UploadView) Index(ctx *web.Context) {
	data := typedef.Dict{
		"TokenUrl":    "/resource/upload/token",
		"QiNiuDomain": cstore.GetDomain(true),
	}
	t, _ := template.ParseFiles("templates/upload-resource.html")
	t.Execute(ctx, data)
}

//need login
func (p UploadView) Token(ctx *web.Context) string {
	var ispub = true
	pubstr, ok := ctx.Params["ispub"]
	if !ok || pubstr == "0" {
		ispub = false
	}
	log.Log.Debug("ispub:%v\n", ispub)
	ses := ctx.Dict["session"].(*models.Session)
	data := typedef.Dict{
		"uptoken": cstore.GetUploadToken(ctx.Request.Host, ispub, ses.UserId),
	}

	return PureJson(data)
}

func (p UploadView) CallBack(ctx *web.Context) string {
	flag, _ := strconv.Atoi(ctx.Params["flag"])
	h, _ := strconv.Atoi(ctx.Params["h"])
	w, _ := strconv.Atoi(ctx.Params["w"])
	size, _ := strconv.Atoi(ctx.Params["size"])
	ispub := ctx.Params["ispub"] == "1"

	r := &models.Resource{
		Flag:   flag,
		Public: ispub,
		Fname:  ctx.Params["fname"],
		Bucket: ctx.Params["bucket"],
		Key:    ctx.Params["key"],
		Hash:   ctx.Params["hash"],
		Mime:   ctx.Params["type"],
		Size:   size,
		Height: h,
		Width:  w,
		UserId: ctx.Params["uuid"],
	}
	err := service.ResourceService.SaveResource(r)
	var data typedef.Dict
	if err != nil {
		data = typedef.Dict{
			"success": false,
			"msg":     err.Error(),
		}
	} else {
		data = typedef.Dict{
			"success":  true,
			"hash":     ctx.Params["hash"],
			"key":      ctx.Params["key"],
			"mime":     ctx.Params["type"],
			"imageAve": ctx.Params["imageAve"],
		}
	}

	//七牛的回调，必须参照七牛的格式定
	return PureJson(data)
}
